<template>
  <el-upload
    class="upload-demo"
    :class="{disableDel:isDisableDel}"
    :action="fileUploadApi"
    :before-upload="beforeUpload"
    :before-remove="beforeRemove"
    :on-remove="handleRemove"
    :headers="headers"
    multiple
    :on-success="handleSuccess"
    :on-preview="handlePreview"
    :file-list="fileList"
    :limit="limit"

  >
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">文件大小不超过20M</div>
  </el-upload>
</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'
import { downloadTheFile } from '@/utils'

export default {
  name: 'Uploader',
  props: {
    limit: null,
    theFileList: {
      type: Array,
      default: () => {
        return []
      }
    },
    isDisableDel: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      headers: {
        token: getToken()
      },
      fileList: this.theFileList,
      isOverSize: false,
    }
  },

  computed: {
    ...mapGetters(['fileUploadApi', 'fileDownloadApi'])
  },
  methods: {
    beforeRemove(file, fileList) {
      if (!this.isOverSize) {
        return this.$confirm(`确定移除 ${file.name}？`)
      }
    },
    handleRemove(file, fileList) {
      this.$emit('updateFileList', fileList)
    },
    handleSuccess(response, file, fileList) {
      if (response.code !== 0) {
        Message({
          message: response.msg || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
        file.status = 'fail'
        fileList.splice(fileList.indexOf(file), 1)
      } else {
        file.fileId = response.fileId

        this.$emit('updateFileList', fileList)
      }
    },
    beforeUpload(file) {
      const isLt20M = file.size / 1024 / 1024 < 20;

      if (!isLt20M) {
        this.isOverSize = true;
        this.$message.error('上传文件大小不能超过 20MB!');
      } else {
        this.isOverSize = false;
      }
      return isLt20M;
    },
    handlePreview(file) {
      downloadTheFile(`/business/file/download?fileId=${file.fileId}`, file.name)
    }
  }
}
</script>

<style lang="scss" scoped>
.disableDel{
 ::v-deep .el-icon-close{
   display:none;
 }
  ::v-deep .el-icon-close-tip{
    display:none;
  }
}
</style>
